import { Card, message, Modal, Form, InputNumber, Button } from 'antd'
import { PercentageOutlined, DeleteOutlined } from '@ant-design/icons'
import { $api } from '@/http/api'
import React, { useState } from 'react'
import { useParams } from 'react-router-dom'

const { Meta } = Card;

const FoodItem = (props) => {
  const formRef = React.createRef()

  const [isModalVisible, setIsModalVisible] = useState(false);

  const [afterDiscount, setAfterDiscount] = useState(props.price);

  const showModal = () => {
    setIsModalVisible(true);
  };

  const params = useParams()

  const handleCancel = () => {
    formRef.current.resetFields()
    setIsModalVisible(false);
    setAfterDiscount(props.price)
  };

  const _delete = () => {
    $api.manager.deleteFood({
      id: props.id
    }).then((res) => {
      if (res.code === 200) {
        message.success('Successfully delete it')
        props.refresh()
      }
    })
  }

  const newDiscount = (values) => {
    $api.manager.newDiscount({
      discount: values.discount,
      food_id: props.id,
      restaurant_id: params.id,
    }).then((res) => {
      if (res.code === 200) {
        message.success('Successfully add discount')
        props.refresh()
        handleCancel()
      }
    })
  }

  const onValuesChange = (values) => {
    setAfterDiscount(props.price * values.discount)
  }

  const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };

  let description = props.discount < 1 ?
    <>
      <span className='line-through'>💷 {props.price}</span>
      <span> {`[${props.discount * 100}%]`} 💷 {props.price * props.discount} 🥡 {props.description}</span>
    </>
    :
    <span>💷 {props.price} 🥡 {props.description}</span>

  return (
    <>
      <Card hoverable
        cover={<img alt={props.name} src={props.img} />}
        actions={[
          <PercentageOutlined key="edit" onClick={showModal} />,
          <DeleteOutlined key="delete" onClick={_delete} />,
        ]}>
        <Meta title={props.name} description={description} />
      </Card>
      <Modal title="Basic Modal" visible={isModalVisible} onCancel={handleCancel} footer={null}>
        <Form {...layout} ref={formRef} name="discount" onFinish={newDiscount} onValuesChange={onValuesChange} initialValues={{ discount: 1 }}>
          <Form.Item
            label="Discount"
            name="discount"
            rules={[{ required: true, message: 'Please input the discount!' }]}>
            <InputNumber min={0} max={1} />
          </Form.Item>
          <Form.Item label="Before">
            {props.price}
          </Form.Item>
          <Form.Item label="After">
            {afterDiscount}
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button onClick={handleCancel} className='mr-4'>Cancel</Button>
            <Button type="primary" htmlType="submit">Submit</Button>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}

export default FoodItem
